package com.lzb.browser.adapter;

import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.Utils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.provider.BaseItemProvider;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.lzb.browser.R;
import com.lzb.browser.basic.ProviderMultiAdapter;
import com.lzb.browser.bean.CollectBean;
import com.lzb.browser.utils.IconDownloadTask;
import com.lzb.browser.utils.IconUtils;

public class CollectAdapter extends ProviderMultiAdapter<CollectBean> {

    private boolean isEdit;

    public CollectAdapter() {
        addItemProvider(new CollectProvider());
    }

    public void setEdit(boolean edit) {
        isEdit = edit;
    }

    private class CollectProvider extends BaseItemProvider<CollectBean> {
        @Override
        public int getItemViewType() {
            return ProviderMultiAdapter.TYPE_VIEW;
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_collect;
        }

        @Override
        public void convert(@NonNull BaseViewHolder baseViewHolder, CollectBean bean) {
            baseViewHolder.setText(R.id.tvCollectItemTitle, bean.getTitle());
            baseViewHolder.setText(R.id.tvCollectItemUrl, bean.getUrl());

            ImageView ivIcon = baseViewHolder.getView(R.id.ivCollectItemIcon);

            // 加载图标
            loadIcon(ivIcon, bean);
            if (isEdit) {
                baseViewHolder.getView(R.id.ivCollectItemSel).setVisibility(View.VISIBLE);
                baseViewHolder.getView(R.id.ivCollectItemEdit).setVisibility(View.VISIBLE);
                baseViewHolder.getView(R.id.ivCollectItemSort).setVisibility(View.VISIBLE);
                if (bean.isSelected()) {
                    baseViewHolder.setImageResource(R.id.ivCollectItemSel, R.drawable.select);
                } else {
                    baseViewHolder.setImageResource(R.id.ivCollectItemSel, R.drawable.no_select);
                }
            } else {
                baseViewHolder.getView(R.id.ivCollectItemSel).setVisibility(View.GONE);
                baseViewHolder.getView(R.id.ivCollectItemEdit).setVisibility(View.GONE);
                baseViewHolder.getView(R.id.ivCollectItemSort).setVisibility(View.GONE);
            }
        }
    }

    /**
     * 加载图标
     */
    private void loadIcon(ImageView ivIcon, CollectBean item) {
        // 优先使用保存的图标数据
        if (!TextUtils.isEmpty(item.getIconData())) {
            Bitmap iconBitmap = IconUtils.base64ToBitmap(item.getIconData());
            if (iconBitmap != null) {
                ivIcon.setImageBitmap(iconBitmap);
                return;
            }
        }

        if (!TextUtils.isEmpty(item.getIconUrl())) {
            // 使用图标URL加载，同时下载并保存
            RequestOptions options = new RequestOptions()
                    .error(R.drawable.bd)
                    .placeholder(R.drawable.bd)
                    .transform(new RoundedCorners(8));

            Glide.with(Utils.getApp())
                    .load(item.getIconUrl())
                    .apply(options)
                    .into(ivIcon);

            // 异步下载图标并保存
            downloadAndSaveIcon(item);
        } else {
            // 加载默认图标
            loadDefaultIcon(ivIcon, item.getUrl());
        }
    }

    /**
     * 下载并保存图标
     */
    private void downloadAndSaveIcon(CollectBean item) {
        new IconDownloadTask(Utils.getApp(), new IconDownloadTask.OnIconDownloadListener() {
            @Override
            public void onIconDownloaded(Bitmap bitmap, String iconUrl) {
                // 将图标转换为Base64
                String iconData = IconUtils.bitmapToBase64(bitmap);
                if (iconData != null) {
                    item.setIconData(iconData);
                    // 通知数据更新
                    notifyDataSetChanged();
                }
            }

            @Override
            public void onIconDownloadFailed(String iconUrl) {
                // 图标下载失败，保持默认图标
            }
        }).execute(item.getIconUrl());
    }

    private void loadDefaultIcon(ImageView imageView, String url) {
        // 生成网站的首字母作为默认图标
        String domain = extractDomain(url);
        String firstChar = domain.isEmpty() ? "W" : domain.substring(0, 1).toUpperCase();

        // 这里可以创建一个带有首字母的默认图标
        // 暂时使用默认的网页图标
        imageView.setImageResource(R.drawable.bd);
    }

    private String extractDomain(String url) {
        if (url == null || url.isEmpty()) {
            return "";
        }

        try {
            // 简单的域名提取逻辑
            String domain = url.replace("https://", "")
                    .replace("http://", "")
                    .replace("www.", "");

            int slashIndex = domain.indexOf("/");
            if (slashIndex != -1) {
                domain = domain.substring(0, slashIndex);
            }

            return domain;
        } catch (Exception e) {
            return "";
        }
    }
}